package cn.dengfanxin.gae.test.keyword;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class UserValidation extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2419873195580682213L;

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();
//		System.out.println(request.get);
//		System.out.println(request.get);
		String url = (String) request.getParameter("url");
		url = URLDecoder.decode(url,"UTF-8");
		System.out.println("url="+ url);
		System.out.println("user="+user);
		if (null != user){
			out.print("User:"+user.getEmail() +
					 "<a href=\""+userService.createLogoutURL(url)+"\">Log out</a>");
		}else{
			out.print("Guest"+
					"<a href=\""+userService.createLoginURL(url)+"\">Log in</a>");
		}
//		//just test here remove later
//		System.out.println("makePersistance here:now");
//		PersistenceManager pm = PMF.getInstance().getPersistenceManager();
//		try{
//			pm.makePersistent(new Keyword());
//		}finally{
//			pm.close();
//			System.out.println("pm succeed");
//		}
		out.flush();
		out.close();
	}

}
